<?php
namespace app\admin\logic\user;

use app\basic\BaseLogic;
use app\admin\model\user\Vip;
use app\basic\exception\ApiException;

/**
 * 会员卡逻辑层
 */
class VipLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new Vip();
    }

    /**
     * 获取会员卡列表
     * @return array
     */
    public function getVipList(): array
    {
        // 查询会员卡列表
        $list = $this->model->where(['status' => 1])
            ->field('id,name,adv,price,sprice,discount,day')
            ->order('sort DESC, id DESC')
            ->select()
            ->toArray();

        // 处理数据
        foreach ($list as &$item) {
            // 处理价格显示
            $item['price'] = floatval($item['price']);
            $item['sprice'] = floatval($item['sprice']);
            // 计算实际折扣
            if ($item['discount']) {
                $item['discount'] = floatval($item['discount']);
            } else {
                $item['discount'] = $item['sprice'] > 0 ? 
                    round(($item['price'] / $item['sprice']) * 10, 1) : 0;
            }
        }

        return $list;
    }

    /**
     * 获取会员卡权益
     * @param int $vipId 会员卡ID
     * @return array
     * @throws ApiException
     */
    public function getVipRights(int $vipId): array
    {
        // 查询会员卡信息
        $vipInfo = $this->model->where([
            'id' => $vipId,
            'status' => 1
        ])->field('id,name,download,discount,day')->findOrEmpty();
        
        if ($vipInfo->isEmpty()) {
            throw new \exception\ApiException('会员卡不存在或已下架');
        }
        // 转为数组
        $vipInfo = $vipInfo->toArray();
        
        // 处理权益数据
        $rights = [
            'vip_name' => $vipInfo['name'],
            'download' => [
                'name' => '下载次数',
                'value' => intval($vipInfo['download']),
                'unit' => '次/天'
            ],
            'discount' => [
                'name' => '会员折扣',
                'value' => floatval($vipInfo['discount']),
                'unit' => '折'
            ],
            'duration' => [
                'name' => '有效期',
                'value' => intval($vipInfo['day']),
                'unit' => '天'
            ]
        ];
        
        return $rights;
    }
} 